<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			* {
				margin: 0px;
				padding: 0px;
			}

			body {
				background-color: #e4e7ed;
				padding: 20px;
			}

			.box-card {
				height: calc(100vh - 100px);
			}

			#app {
				margin: auto;
				max-width: 500px;
			}

			.my-tag {
				margin-bottom: 10px;
				display: flow-root;
			}

			.my-tag .el-tag {
				word-wrap: break-word;
				word-break: break-all;
				overflow: hidden;
				max-width: 300px;
			}

			.my-tag-class {
				float: right;
			}
		</style>
		<link rel="stylesheet" href="css/ele.2.15.6.css">
	</head>
	<body>
		<div id="app">
			<el-card class="box-card">
				<div v-for="item in msgList" class="my-tag">
					<el-tag :class="id == item.id ? 'my-tag-class' : ''" :type="id == item.id ? '' : 'warning'">
						{{ !item.id ? '机器人' : item.id  + ' : ' + item.message }}
					</el-tag>
				</div>
			</el-card>
			<div>
				<el-input placeholder="请输入内容" v-model="inputValue">
					<el-button slot="append" @click="sendMessage"> 发送 </el-button>
				</el-input>
			</div>
		</div>
	</body>
	<script src="js/vue.min.js" type="text/javascript" charset="utf-8"></script>
	<script src="js/ele.2.15.6.js"></script>
	<script type="text/javascript">
		new Vue({
			el: '#app',
			data: function() {
				return {
					ws: {},
					msgList: [],
					inputValue: '你好！',
					id: ''
				}
			},
			mounted() {
				this.id = getQueryVariable("id");

				if ("WebSocket" in window) {
					// 打开一个 web socket
					var ws = new WebSocket("ws://127.0.0.1:8080/ws/" + this.id);
					this.ws = ws;
					ws.onopen = this.onopen;
					ws.onmessage = this.onmessage;
					ws.onclose = this.onclose;
				} else {
					// 浏览器不支持 WebSocket
					alert("您的浏览器不支持 WebSocket!");
				}
			},
			methods: {
				onopen() {

				},
				onmessage(val) {
					var data = JSON.parse(val.data);
					console.log(data)
					this.msgList.push(data);
				},
				onclose() {

				},
				sendMessage() {
					if (this.inputValue) {
						this.ws.send(JSON.parse(JSON.stringify(this.inputValue)));
						this.inputValue = '';
					}
				}
			}
		});

		function getQueryVariable(variable) {
			var query = window.location.search.substring(1);
			var vars = query.split("&");
			for (var i = 0; i < vars.length; i++) {
				var pair = vars[i].split("=");
				if (pair[0] == variable) {
					return pair[1];
				}
			}
			return (false);
		}

		//事件
		/* open 	Socket.onopen 	连接建立时触发
		 message 	Socket.onmessage 	客户端接收服务端数据时触发
		 error 	Socket.onerror 	通信发生错误时触发
		 close 	Socket.onclose 	连接关闭时触发*/

		//方法
		/*Socket.send()
		使用连接发送数据
		Socket.close()
		关闭连接*/
	</script>
</html>
